<script lang="ts" setup>
import { ref, defineEmits } from 'vue';
import axios from 'axios';

const emit = defineEmits<{
  close: []; // 关闭弹窗事件
  loginSuccess: [{ username: string }]; // 登录成功事件，传递用户名
}>();

const isLoginMode = ref(true); // true 为登录模式，false 为注册模式
const username = ref('');   // 用户名
const password = ref('');   // 密码
const confirmPassword = ref('');   // 确认密码
const usernameError = ref('');   // 用户名错误信息
const passwordError = ref('');   // 密码错误信息
const confirmPasswordError = ref('');   // 确认密码错误信息
const realName = ref(''); // 真实姓名
const realNameError = ref(''); // 真实姓名错误信息  
const phone = ref(''); // 电话
const phoneError = ref(''); // 电话错误信息
const idCard = ref(''); // 身份证号
const idCardError = ref(''); // 身份证号错误信息


const isLoading = ref(false); // 加载锁，防止重复请求



// 切换登录/注册模式
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value;
  // 清空表单和错误信息
  resetForm();
};

// 重置表单
const resetForm = () => {
  username.value = '';
  password.value = '';
  confirmPassword.value = '';
  usernameError.value = '';
  passwordError.value = '';
  confirmPasswordError.value = '';
  realName.value = '';
  idCard.value = '';
};

// 表单验证
const validateForm = (): boolean => {
  let isValid = true;
  
  // 用户名验证
  if (!username.value.trim()) {
    usernameError.value = '请输入用户名';
    isValid = false;
  } else if (username.value.length < 3 || username.value.length > 20) {
    usernameError.value = '用户名长度应在3-20个字符之间';
    isValid = false;
  } else {
    usernameError.value = '';
  }
  
  // 密码验证
  if (!password.value) {
    passwordError.value = '请输入密码';
    isValid = false;
  } else if (password.value.length < 1) {
    passwordError.value = '密码长度至少为1个字符';
    isValid = false;
  } else {
    passwordError.value = '';
  }
  
  // 注册模式下验证确认密码
  if (!isLoginMode.value && password.value !== confirmPassword.value) {
    confirmPasswordError.value = '两次输入的密码不一致';
    isValid = false;
  } else {
    confirmPasswordError.value = '';
  }
  
  

  // 真实姓名验证
  if (!realName.value.trim()) {
    realNameError.value = '请输入真实姓名';
    isValid = false;
    
  } else if (realName.value.length < 2 || realName.value.length > 10) {
    realNameError.value = '真实姓名长度应在2-10个字符之间';
    isValid = false;
  } else {
    realNameError.value = '';
  }
  
  // 电话验证
  if (!phone.value.trim()) {
    phoneError.value = '请输入电话';
    isValid = false;
  } else if (!/^1[3456789]\d{9}$/.test(phone.value)) {
    phoneError.value = '请输入正确的电话号';
    isValid = false;
  } else {
    phoneError.value = '';
  }
  
  // 身份证号验证
  if (!idCard.value.trim()) {
    idCardError.value = '请输入身份证号';
    isValid = false;
  } else if (!/^\d{17}[\dXx]|\d{15}$/.test(idCard.value)) {
    idCardError.value = '请输入正确的身份证号';
    isValid = false;
  } else {
    idCardError .value = '';
  }
  return isValid;
};

// 关闭弹窗
const handleClose = () => {
  resetForm();
  emit('close');
};


import {useLoginStore} from '@/stores/LoginStore'
const logingStore = useLoginStore()

//向服务器发送登录请求
// 登录请求
const loginRequest = async () => {

  if (isLoading.value) return; // 已有请求在进行，直接返回
  isLoading.value = true;

  // 验证表单
  // if (!validateForm()) return;
  if(isLoginMode.value){
    // 登录请求
    try {
      const response = await axios.post('/api/user/login', {
        username: username.value,
        password: password.value
        
      });
      if (response.data.code==200) {
        emit('loginSuccess', { username: username.value });
        alert('登录成功');
        //存储token
        logingStore.setTokenAndUsernaeme(response.data.data.token,response.data.data.username)
        resetForm();
        emit('close');
      } else {
        usernameError.value = '用户名或密码错误';
      }
    } catch (error) {
      console.error('登录请求失败:', error);
      usernameError.value = '登录请求失败，请稍后重试';
    }
  }else{
    // 注册请求
    try {
      const response = await axios.post('/api/user/register', {
        username: username.value,
        password: password.value,
        confirmPassword: confirmPassword.value,
        realName: realName.value,
        idCard: idCard.value,
        phone: phone.value
      });
      if (response.data.code==200) {
        emit('loginSuccess', { username: username.value });
        alert('注册成功');
        resetForm();
        emit('close');
      } else {
        usernameError.value = '注册失败，请检查信息';
      }
    } catch (error) {
      console.error('注册请求失败:', error);
      usernameError.value = '注册请求失败，请稍后重试';
    }
  }
  
};
</script>

<template>
  <div class="modal-overlay" @click.self="handleClose">
    <div class="modal-container">
      <div class="modal-header">
        <h3>{{ isLoginMode ? '登录' : '注册' }}</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="loginRequest ">
          <div class="form-group">
            <label for="username">用户名</label>
            <input
              id="username"
              type="text"
              v-model="username"
              placeholder="请输入用户名"
              @input="usernameError = ''"
            />
            <div v-if="usernameError" class="error-message">{{ usernameError }}</div>
          </div>
          
          <div class="form-group">
            <label for="password">密码</label>
            <input
              id="password"
              type="password"
              v-model="password"
              placeholder="请输入密码"
              @input="passwordError = ''"
            />
            <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
          </div>
          
          <div v-if="!isLoginMode" class="form-group">
            <label for="confirmPassword">确认密码</label>
            <input
              id="confirmPassword"
              type="password"
              v-model="confirmPassword"
              placeholder="请再次输入密码"
              @input="confirmPasswordError = ''"
            />
            <div v-if="confirmPasswordError" class="error-message">{{ confirmPasswordError }}</div>
          </div>
          <div class="form-group" v-if="!isLoginMode">
            <label>真实姓名</label>
            <input
              type="text"
              v-model="realName"
              placeholder="请输入真实姓名"
            />
            <div v-if="realNameError" class="error-message">{{ realNameError }}</div>
          </div>
          <div  class="form-group" v-if="!isLoginMode">
            <label>电话</label>
            <input
              type="text"
              v-model="phone"
              placeholder="请输入电话"
            />
            <div v-if="phoneError" class="error-message">{{ phoneError }}</div>
          </div>

          <div class="form-group" v-if="!isLoginMode">
            <label>身份证号</label>
            <input
              type="text"
              v-model="idCard"
              placeholder="请输入身份证号"
            />
            <div v-if="idCardError" class="error-message">{{ idCardError }}</div>
          </div>

          <button type="submit" class="submit-btn" @click="loginRequest">{{ isLoginMode ? '登录' : '注册' }}</button>
        </form>
        
        <div class="toggle-mode">
          <span> {{ isLoginMode ? '还没有账号？' : '已有账号？' }} </span>
          <button class="toggle-btn" @click="toggleMode">
            {{ isLoginMode ? '立即注册' : '立即登录' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
}

.close-btn:hover {
  background-color: #f5f5f5;
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #666;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
  transition: border-color 0.2s;
}

.form-group input:focus {
  outline: none;
  border-color: #409eff;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  margin-top: 10px;
}

.submit-btn:hover {
  background-color: #66b1ff;
}

.toggle-mode {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
  color: #666;
}

.toggle-btn {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
  padding: 0;
  margin-left: 5px;
}

.toggle-btn:hover {
  color: #66b1ff;
  text-decoration: underline;
}
</style>